//
//  USWaveBarView.m
//

#import "USWaveBarView.h"

@interface USWaveBarView ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) CGFloat barWidth;
@property (nonatomic, assign) CGFloat spacing;
@property (nonatomic, strong) NSMutableArray<UIView *> *barCache; // 缓存池
@property (nonatomic, assign) NSInteger maxCachedBars;
@property (nonatomic, strong) CADisplayLink *displayLink;

@end

@implementation USWaveBarView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _barWidth = 3;
        _spacing = 3;
        _maxCachedBars = 100;
        _barCache = [NSMutableArray array];
        
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.userInteractionEnabled = NO;
        [self addSubview:_scrollView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
}

- (void)addBarWithVolume:(CGFloat)volume {
    
    if (!self.displayLink) {
        [self start];
    }
    
    volume = MAX(0, MIN(volume, 1));
    CGFloat maxHeight = self.bounds.size.height;
    CGFloat targetHeight = MAX(4, volume * maxHeight);
    CGFloat centerY = maxHeight / 2.0;
    CGFloat x = self.scrollView.contentSize.width;

    UIView *bar = [self dequeueBar];
    bar.backgroundColor = UIColor.whiteColor;
    bar.frame = CGRectMake(x, centerY, self.barWidth, 0); // 初始高度为0
    [self.scrollView addSubview:bar];

    // 动画伸展
    [UIView animateWithDuration:0.3 animations:^{
        bar.frame = CGRectMake(x, centerY - targetHeight / 2.0, self.barWidth, targetHeight);
    }];
    
    //这是0.1秒内的变化值
    CGFloat newContentWidth = self.scrollView.contentSize.width + self.barWidth + self.spacing;
    self.scrollView.contentSize = CGSizeMake(newContentWidth, self.bounds.size.height);
    
}

- (void)start {
    [self stop];
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateWave)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)stop {
    [self.displayLink invalidate];
    self.displayLink = nil;
}

- (void)updateWave {
    
    if (self.scrollView.contentSize.width <= self.scrollView.bounds.size.width) return;
    // 每帧偏移距离 = 单条宽度 * 每帧时间 / 添加周期 (0.1秒)
    CGFloat perFrameDistance = (self.barWidth + self.spacing) * (self.displayLink.duration / 0.1);

    CGFloat targetOffsetX = self.scrollView.contentOffset.x + perFrameDistance;
    CGFloat maxOffsetX = self.scrollView.contentSize.width - self.scrollView.bounds.size.width;

    if (targetOffsetX > maxOffsetX) {
        targetOffsetX = maxOffsetX;
    }
    [self.scrollView setContentOffset:CGPointMake(targetOffsetX, 0) animated:NO];
    
}

- (UIView *)dequeueBar {
    UIView *bar;
    if (self.barCache.count > 0) {
        bar = self.barCache.lastObject;
        [self.barCache removeLastObject];
    } else {
        bar = [[UIView alloc] init];
        bar.layer.cornerRadius = _barWidth * 0.5;
        bar.clipsToBounds = YES;
    }
    return bar;
}

- (void)enqueueBar:(UIView *)bar {
    if (self.barCache.count < self.maxCachedBars) {
        [self.barCache addObject:bar];
    }
}

- (void)reset {
    // 回收并缓存所有 bar
    for (UIView *bar in self.scrollView.subviews) {
        [bar removeFromSuperview];
        [self enqueueBar:bar];
    }
    // 清空 scrollView content
    self.scrollView.contentSize = CGSizeMake(0, self.bounds.size.height);
    [self.scrollView setContentOffset:CGPointZero animated:NO];
}

- (void)willMoveToWindow:(UIWindow *)newWindow {
    [super willMoveToWindow:newWindow];
    
    if (newWindow == nil) {
        [self stop]; // 视图即将移除时停止刷新
    }
}


@end
